<template>
    <el-popover placement="bottom" v-model="visible" :disabled="disabled">
        <table cellpadding="0" cellspacing="0" >
            <tr>
                <td>
                    <table class="calendar-table" cellpadding="0" cellspacing="0">
                        <tr v-for="(value, index) in yearList" :key="index">
                            <td
                                v-for="data in value"
                                :key="data.id"
                                @click="clickYear(data)"
                                :class="{selected: data.selected}"
                            >
                                <span>{{data.gradePartOne +'-'+data.gradePartTwo}}</span>
                            </td>
                        </tr>
                    </table>
                    <div v-if="all" class="all" @click="clickAll">{{$t('common.text.all')}}</div>
                </td>
                <td valign="top">
                    <table class="calendar-term-table" cellpadding="0" cellspacing="0">
                        <tr v-for="(data) in termList" :key="data.id">
                            <td
                                @click="clickTerm(data)"
                                :class="{selected: data.selected}"
                            >{{data.perTerm}}</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <div slot="reference">
            <div
                class="el-select"
                :class="[selectSize ? 'el-select--' + selectSize : '']"
                :style="calendarStyle"
                v-if="multiple"
            >
                <div
                    class="el-select__tags"
                    ref="tags"
                    :style="{ 'max-width': inputWidth - 32 + 'px', width: '100%' }"
                >
                    <transition-group @after-leave="resetInputHeight">
                        <el-tag
                            v-for="data in multipleDatas"
                            :key="data.id"
                            :closable="true"
                            type="info"
                            @close="deleteMutiple($event, data)"
                            disable-transitions
                        >
                            <span class="el-select__tags-text">{{ data.fullName }}</span>
                        </el-tag>
                    </transition-group>
                </div>
                <el-input type="text" ref="reference" readonly></el-input>
            </div>
            <el-input
                v-if="!multiple"
                readonly
                @click="visible = !visible"
                :disabled="disabled"
                v-model="labelValue"
                :style="inputStyle"
                :placeholder="$t('common.text.all')"
            >
                <i
                    slot="suffix"
                    class="el-input__icon el-icon-arrow-up"
                    :class="{'is-reverse': visible}"
                ></i>
            </el-input>
        </div>
    </el-popover>
</template>
<script>
import {
    addResizeListener,
    removeResizeListener
} from "element-ui/src/utils/resize-event";
import { valueEquals, isIE, isEdge } from "element-ui/src/utils/util";
import calendars from "common/src/api/calendars";
import UTILS from "common/src/utils/utils";
import { getValue } from "common/src/api/commonParam";

/**
 * 校历下拉框组件
 */
export default {
    name: "CalendarSelect",
    props: {
        value: {
            required: true
        },
        disabled: {
            default: false // 是否禁用
        },
        inputStyle: {
            default: ""
        },
        multiple: {
            default: false // 是否多选
        },
        multipleLimit: {
            type: Number,
            default: 0
        },
        data: {
            // 可以手动传入学期数据，不传时则查询接口
            default: () => []
        },
        selectSize: {
            default: "mini"
        },
        defaulted: {
            // 若为false 则不自动加载默认学期
            type: Boolean,
            default: true
        },
        calendarStyle: {
            type: String,
            default: ""
        },
        all: {
            type: Boolean,
            default: false
        },
        useNextCalender:{
          type: Boolean,
          default:false
        },
        useConfigParam:{
          type: String,
          default: ''
        }
    },
    data() {
        return {
            labelValue: "",
            visible: false,
            yearList: [],
            dataMap: new Map(),
            idYearMap: new Map(),
            termList: [],
            preClickYear: null, //上次点击的年
            preClickTerm: null, //上次点击的学期
            loading: false,
            multipleDatas: [], //
            inputWidth: 0,
            initialInputHeight: 0,
            currentTermId: null
        };
    },
    watch: {
        visible: {
            handler: function(newVal, oldVal) {
                this.onShow();
            }
        },
        value(val, oldVal) {
            this.selectByModel(val);
        }
    },
    methods: {
        selectByModel(modelVal) {
            if (this.multiple) {
                this.multipleDatas = [];
                if (!_.isEmpty(modelVal)) {
                    modelVal.forEach(id => {
                        const year = this.idYearMap.get(id);
                        this.setSelected(year, id);
                    });
                }
                return;
            }
            let id = modelVal;
            const year = this.idYearMap.get(id);
            this.setSelected(year, id);
        },
        setSelected(year, id) {
            if (this.yearList && year) {
                //二维数组
                for (const subList of this.yearList) {
                    for (const data of subList) {
                        if (year == data.year) {
                            this.clickYear(data);
                            break;
                        }
                    }
                }
            } else {
                this.clickYear({});
            }
            if (this.dataMap && id) {
                this.dataMap.forEach(terms => {
                    for (const t of terms) {
                        if (t.id == id) {
                            this.highlightTerm(t);
                            if (this.multiple) {
                                this.addToMultiples(t);
                            }
                        }
                    }
                });
            } else {
                this.highlightTerm({});
            }
        },
        clickYear(data) {
            if (this.preClickYear) {
                this.preClickYear.selected = false;
            }
            if (!_.isEmpty(data)) {
                data.selected = true;
                this.preClickYear = data;
                this.termList = this.dataMap.get(data.year);
                if (this.termList) {
                    this.termList = _.sortBy(this.termList, ["term"]);
                }
            }
        },
        highlightTerm(data) {
            if (this.preClickTerm) {
                this.preClickTerm.selected = false;
            }
            if (!_.isEmpty(data)) {
                data.selected = true;
                this.preClickTerm = data;
                this.labelValue = data.fullName;
            } else {
                this.labelValue = "";
            }
            this.$emit("fullName", this.labelValue);
        },
        clickTerm(data) {
            if (this.multiple) {
                this.multipleClickTerm(data);
            } else {
                this.$emit("input", data.id);
                this.emitChange(data.id);
                this.visible = false;
            }
            this.highlightTerm(data);
        },
        getDataList() {
            return UTILS.cacheCalendarList;
        },
        onShow() {
            if (this.visible) {
                // 当选择了年却没有选择学期时显示上一次记录
                if (
                    this.preClickTerm &&
                    this.preClickTerm.year != this.preClickYear.year
                ) {
                    this.setSelected(this.preClickTerm.year);
                }
            }
        },
        init() {
            if (!_.isEmpty(this.data)) {
                this.processData(this.data);
            } else {
                new Promise((resolve, reject) => {
                    if (this.getDataList()) {
                        resolve(this.getDataList());
                    } else {
                        calendars.listAllCalendar().then(res => {
                            UTILS.cacheCalendarList = res.data;
                            resolve(res.data);
                        });
                    }
                }).then(res => {
                    this.processData(res);
                });
            }
        },
        processData(data) {
            // 把数组处理成显示需要的格式
            this.dataMap = new Map();
            let currentYear = "";
            this.currentTermId = null;
            data.forEach(value => {
                const term = UTILS.clone(value);
                if (this.useNextCalender) {
                    if (term.nextTermFlag) {
                        currentYear = term.year;
                        this.currentTermId = term.id;
                    }
                } else {
                    if (term.currentTermFlag) {
                        currentYear = term.year;
                        this.currentTermId = term.id;
                    }
                }

                this.idYearMap.set(term.id, term.year);

                if (this.dataMap.get(term.year)) {
                    this.dataMap.get(term.year).push(term);
                } else {
                    this.dataMap.set(term.year, [term]);
                }
            });
            const data_ = []; //二维数组，每一行显示4个学年
            let group = [];
            this.dataMap.forEach(terms => {
                const term = UTILS.clone(terms[0]);
                group.push(term);
                if (group.length == 4) {
                    data_.push(group);
                    group = [];
                }
            });
            if (!_.isEmpty(group)) {
                data_.push(group);
            }
            this.yearList = data_;
            if (this.defaulted) {
                // 如果model有值选择model对应的学期
                let defaultValue = !UTILS.isEmpty(this.value)
                    ? this.value
                    : this.multiple
                    ? []
                    : this.currentTermId;
                this.selectByModel(defaultValue);
                // model没有值时默认给当前学期
                if (UTILS.isEmpty(this.value)) {
                    //这里进行是否有配置项的判断
                    if(this.useConfigParam){
                        getValue(this.useConfigParam).then(res=>{
                          if(res.data){
                              this.value = res.data;
                              this.$emit("input", this.value);
                              this.emitChange(this.value);
                              this.$emit("load-done", data, this.currentTermId);
                          }else{
                              this.$emit("input", defaultValue);
                              this.emitChange(defaultValue);
                              this.$emit("load-done", data, this.currentTermId);
                          }
                        })
                    }else{
                       this.$emit("input", defaultValue);
                       this.emitChange(defaultValue);
                       this.$emit("load-done", data, this.currentTermId);
                    }
                }else{
                    this.$emit("load-done", data, this.currentTermId);
                }
            }
        },
        emitChange(newVal) {
            if (!valueEquals(this.value, newVal)) {
                this.$emit("change", newVal);
            }
        },
        deleteMutiple(event, data) {
            let temp = [];
            let newVal = [];
            for (let d of this.multipleDatas) {
                if (d.id != data.id) {
                    temp.push(d);
                    newVal.push(d.id);
                }
            }
            this.$emit("input", newVal);
            this.emitChange(newVal);
            this.multipleDatas = temp;
            this.$nextTick(() => {
                this.resetInputHeight();
            });
            event.stopPropagation();
        },
        addToMultiples(data) {
            for (let d of this.multipleDatas) {
                if (valueEquals(d.id, data.id)) {
                    return false;
                }
            }
            if (
                this.multipleLimit <= 0 ||
                this.multipleDatas.length < this.multipleLimit
            ) {
                this.multipleDatas.push(data);
                this.$nextTick(() => {
                    this.resetInputHeight();
                });
                return true;
            }
            return false;
        },
        multipleClickTerm(data) {
            if (data && this.addToMultiples(data)) {
                let newVal = [];
                for (let d of this.multipleDatas) {
                    newVal.push(d.id);
                }
                this.$emit("input", newVal);
                this.emitChange(newVal);
            }
        },
        resetInputWidth() {
            if (this.$refs.reference && this.$refs.reference.$el) {
                this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
            }
        },
        handleResize() {
            this.resetInputWidth();
            if (this.multiple) this.resetInputHeight();
        },
        resetInputHeight() {
            this.$nextTick(() => {
                if (!this.$refs.reference) return;
                let inputChildNodes = this.$refs.reference.$el.childNodes;
                let input = [].filter.call(
                    inputChildNodes,
                    item => item.tagName === "INPUT"
                )[0];
                const tags = this.$refs.tags;
                const sizeInMap = this.initialInputHeight || 40;
                input.style.height =
                    this.multipleDatas.length === 0
                        ? sizeInMap + "px"
                        : Math.max(
                              tags
                                  ? tags.clientHeight +
                                        (tags.clientHeight > sizeInMap ? 6 : 0)
                                  : 0,
                              sizeInMap
                          ) + "px";
            });
        },
        getLabelValue() {
            return this.labelValue;
        },
        getCurrent() {
            // 获取当前选择学期
            return this.preClickTerm;
        },
        clickAll() {
            this.currentTermId = null;
            this.labelValue = null;
            if (this.preClickYear) {
                this.preClickYear.selected = false;
            }
            if (this.preClickTerm) {
                this.preClickTerm.selected = false;
            }
            this.visible = false;
            this.termList = [];
            this.$emit("input", null);
            this.$emit("change", null);
        }
    },
    created() {
        if (this.multiple && !Array.isArray(this.value)) {
            this.$emit("input", []);
        }
        if (!this.multiple && Array.isArray(this.value)) {
            this.$emit("input", "");
        }
    },
    mounted() {
        // 多选处理
        addResizeListener(this.$el, this.handleResize);
        const reference = this.$refs.reference;
        if (reference && reference.$el) {
            const sizeMap = {
                medium: 36,
                small: 32,
                mini: 28
            };
            this.initialInputHeight =
                reference.$el.getBoundingClientRect().height ||
                sizeMap[this.selectSize];
        }
        this.$nextTick(() => {
            if (reference && reference.$el) {
                this.inputWidth = reference.$el.getBoundingClientRect().width;
            }
        });
        this.init();
    },
    beforeDestroy() {
        if (this.$el && this.handleResize)
            removeResizeListener(this.$el, this.handleResize);
    }
};
</script>

<style lang="scss" scoped>
.calendar-table {
    td {
        padding: 2px 7px;
        cursor: pointer;
        &:hover,
        &.selected {
            color: red;
        }
    }
}
.calendar-term-table {
    td {
        padding: 2px 7px;
        cursor: pointer;
        &:hover,
        &.selected {
            color: red;
        }
    }
}
.el-input__icon.el-icon-arrow-up {
    -webkit-transition: -webkit-transform 0.3s;
    transition: -webkit-transform 0.3s;
    transition: transform 0.3s;
    transition: transform 0.3s, -webkit-transform 0.3s;
    transition: transform 0.3s, -webkit-transform 0.3s;
    -webkit-transform: rotateZ(180deg);
    transform: rotateZ(180deg);
    &.is-reverse {
        -webkit-transform: rotateZ(0);
        transform: rotateZ(0);
    }
}
.all {
    padding: 2px 8px;
    cursor: pointer;
    &:hover {
        color: red;
    }
}
</style>
